<template>
  <div class="seller-login-container">
    <!-- 左侧品牌展示区域 -->
    <div class="left-section">
      <div class="brand-content">
        <h1 class="brand-title">商家管理后台</h1>
        <p class="brand-subtitle">专业的商家管理平台，助力您的业务增长</p>
        <div class="features">
          <div class="feature-item">
            <i class="feature-icon">📊</i>
            <span>数据分析</span>
          </div>
          <div class="feature-item">
            <i class="feature-icon">📦</i>
            <span>商品管理</span>
          </div>
          <div class="feature-item">
            <i class="feature-icon">💰</i>
            <span>订单管理</span>
          </div>
          <div class="feature-item">
            <i class="feature-icon">🎯</i>
            <span>营销推广</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧登录区域 -->
    <div class="right-section">
      <div class="login-content">
        <!-- 登录表单 -->
        <div v-if="!isRegisterMode && !isForgotPasswordMode" class="form-container">
          <div class="login-header">
            <h2>商家登录</h2>
            <p>欢迎使用商家管理后台</p>
          </div>

          <form class="login-form" @submit.prevent="handleLogin">
            <div class="form-group">
              <input
                v-model="loginForm.username"
                type="text"
                placeholder="商家账号/手机号"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="loginForm.password"
                type="password"
                placeholder="登录密码"
                class="form-input"
                required
              />
            </div>

            <div class="form-options">
              <label class="checkbox-wrapper">
                <input v-model="loginForm.rememberMe" type="checkbox" />
                <span class="checkmark"></span>
                记住登录状态
              </label>
              <a href="#" class="forgot-password" @click.prevent="goToForgotPassword">忘记密码？</a>
            </div>

            <button type="submit" class="login-button" :disabled="loading">
              <span v-if="loading">登录中...</span>
              <span v-else>立即登录</span>
            </button>
          </form>

          <div class="register-link">
            还没有商家账户？<a href="#" @click="goToRegister">申请入驻</a>
          </div>

          <div class="help-section">
            <div class="divider">
              <span>需要帮助？</span>
            </div>
            <div class="help-buttons">
              <button class="help-btn">
                <i class="help-icon">📞</i>
                联系客服
              </button>
              <button class="help-btn">
                <i class="help-icon">📖</i>
                入驻指南
              </button>
            </div>
          </div>

          <!-- 客户登录入口 -->
          <div class="customer-entrance">
            <div class="divider">
              <span>普通用户</span>
            </div>
            <button class="customer-login-btn" @click="goToCustomerLogin">
              <i class="customer-icon">👤</i>
              客户登录入口
            </button>
          </div>
        </div>

        <!-- 注册表单 -->
        <div v-else-if="isRegisterMode" class="form-container">
          <div class="register-header">
            <h2>商家入驻申请</h2>
            <p>填写以下信息，开启您的电商之旅</p>
          </div>

          <form class="register-form" @submit.prevent="handleRegister">
            <div class="form-group">
              <input
                v-model="registerForm.shopName"
                type="text"
                placeholder="店铺名称"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="registerForm.contactName"
                type="text"
                placeholder="联系人姓名"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="registerForm.phone"
                type="tel"
                placeholder="联系手机号"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="registerForm.email"
                type="email"
                placeholder="邮箱地址"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="registerForm.password"
                type="password"
                placeholder="设置密码"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="确认密码"
                class="form-input"
                required
              />
            </div>

            <div class="form-options">
              <label class="checkbox-wrapper">
                <input v-model="registerForm.agreeTerms" type="checkbox" />
                <span class="checkmark"></span>
                我同意<a href="#" class="terms-link">商家入驻协议</a>和<a href="#" class="terms-link">平台服务条款</a>
              </label>
            </div>

            <button type="submit" class="register-button" :disabled="loading">
              <span v-if="loading">提交申请中...</span>
              <span v-else>提交入驻申请</span>
            </button>
          </form>

          <div class="login-link">
            已有商家账户？<a href="#" @click="goToLogin">立即登录</a>
          </div>
        </div>

        <!-- 忘记密码表单 -->
        <div v-else-if="isForgotPasswordMode" class="form-container">
          <div class="register-header">
            <h2>商家密码重置</h2>
            <p>请填写您的商家账号信息重置密码</p>
          </div>

          <form class="register-form" @submit.prevent="handleForgotPassword">
            <div class="form-group">
              <input
                v-model="forgotPasswordForm.username"
                type="text"
                placeholder="商家账号"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="forgotPasswordForm.phone"
                type="tel"
                placeholder="联系手机号"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="forgotPasswordForm.newPassword"
                type="password"
                placeholder="新密码（6-10位）"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="forgotPasswordForm.confirmPassword"
                type="password"
                placeholder="确认新密码"
                class="form-input"
                required
              />
            </div>

            <button type="submit" class="register-button" :disabled="loading">
              <span v-if="loading">重置中...</span>
              <span v-else>确认重置</span>
            </button>
          </form>

          <div class="login-link">
            想起密码了？<a href="#" @click.prevent="goToLogin">返回登录</a>
          </div>
        </div>
      </div>
    </div>

    <!-- Toast 提示组件 -->
    <div v-if="toast.show" :class="['toast', toast.type]">
      <div class="toast-content">
        <i :class="['toast-icon', getToastIcon(toast.type)]"></i>
        <span class="toast-message">{{ toast.message }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { sellerRegister, sellerLogin } from '@/api/seller'
import { updatePassword } from '@/api/user'

export default {
  name: 'SellerLogin',
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const isRegisterMode = ref(false) // 控制显示登录还是注册表单
    const isForgotPasswordMode = ref(false) // 控制显示忘记密码表单

    // Toast 提示相关
    const toast = reactive({
      show: false,
      message: '',
      type: 'success' // success, error, warning, info
    })

    // 忘记密码表单数据
    const forgotPasswordForm = reactive({
      username: '',
      phone: '',
      newPassword: '',
      confirmPassword: ''
    })

    const loginForm = reactive({
      username: '',
      password: '',
      rememberMe: false
    })

    const registerForm = reactive({
      shopName: '',
      contactName: '',
      phone: '',
      email: '',
      password: '',
      confirmPassword: '',
      agreeTerms: false
    })

    const handleLogin = async () => {
      if (!loginForm.username || !loginForm.password) {
        showToast('请填写商家账号和密码', 'warning')
        return
      }

      loading.value = true

      try {
        const result = await sellerLogin({
          name: loginForm.username,
          password: loginForm.password
        })

        if (result.status) {
          // 保存商家登录信息
          const sellerInfo = result?.data ?? {}
          const token = result?.data?.token || ''

          // 从 roles 中获取 sellerId
          let sellerId = ''
          if (result?.data?.roles && result.data.roles.length > 0) {
            sellerId = String(result.data.roles[0].id || '')
          }

          localStorage.setItem('sellerInfo', JSON.stringify(sellerInfo))
          localStorage.setItem('sellerToken', token)
          localStorage.setItem('sellerId', sellerId)
          // 保存商家名和logo用于导航栏显示
          localStorage.setItem('shopName', result?.data?.shopName || '')
          localStorage.setItem('logoUrl', result?.data?.logoUrl || '')

          showToast('商家登录成功！', 'success')
          // 延迟跳转，让用户看到成功提示
          setTimeout(() => {
            router.push('/sales-analytics')
          }, 800)
        } else {
          showToast(result.message || '登录失败，请检查账号或密码', 'error')
        }
      } catch (error) {
        console.error('商家登录请求失败:', error)
        showToast(error.message || '网络错误，请检查后端服务是否启动', 'error')
      } finally {
        loading.value = false
      }
    }

    const handleRegister = async () => {
      if (!registerForm.shopName || !registerForm.contactName || !registerForm.phone || !registerForm.email || !registerForm.password) {
        showToast('请填写所有必填字段', 'warning')
        return
      }

      if (registerForm.password !== registerForm.confirmPassword) {
        showToast('两次输入的密码不一致', 'warning')
        return
      }

      if (!registerForm.agreeTerms) {
        showToast('请同意商家入驻协议', 'warning')
        return
      }

      loading.value = true

      try {
        const result = await sellerRegister({
          shopName: registerForm.shopName,
          contactName: registerForm.contactName,
          phone: registerForm.phone,
          email: registerForm.email,
          password: registerForm.password
        })

        if (result.status) {
          showToast('入驻申请提交成功！我们将在3个工作日内审核您的申请。', 'success', 4000)
          isRegisterMode.value = false // 注册成功后切换到登录模式
          // 清空表单
          registerForm.shopName = ''
          registerForm.contactName = ''
          registerForm.phone = ''
          registerForm.email = ''
          registerForm.password = ''
          registerForm.confirmPassword = ''
          registerForm.agreeTerms = false
        } else {
          showToast(result.message || '入驻申请提交失败，请重试', 'error')
        }
      } catch (error) {
        console.error('商家注册请求失败:', error)
        showToast(error.message || '网络错误，请检查后端服务是否启动', 'error')
      } finally {
        loading.value = false
      }
    }

    const goToRegister = () => {
      isRegisterMode.value = true
    }

    const goToLogin = () => {
      isRegisterMode.value = false
      isForgotPasswordMode.value = false
    }

    const goToCustomerLogin = () => {
      router.push('/customer-login')
    }

    const goToForgotPassword = () => {
      isRegisterMode.value = false
      isForgotPasswordMode.value = true
    }

    // Toast 提示方法
    const showToast = (message, type = 'success', duration = 3000) => {
      toast.message = message
      toast.type = type
      toast.show = true

      setTimeout(() => {
        toast.show = false
      }, duration)
    }

    // 处理忘记密码
    const handleForgotPassword = async () => {
      if (!forgotPasswordForm.username || !forgotPasswordForm.phone || !forgotPasswordForm.newPassword) {
        showToast('请填写所有必填字段', 'warning')
        return
      }

      if (forgotPasswordForm.newPassword !== forgotPasswordForm.confirmPassword) {
        showToast('两次输入的密码不一致', 'warning')
        return
      }

      loading.value = true

      try {
        const result = await updatePassword({
          name: forgotPasswordForm.username,
          phone: forgotPasswordForm.phone,
          newPassword: forgotPasswordForm.newPassword
        })

        if (result.status) {
          showToast('密码重置成功！请使用新密码登录', 'success')
          // 延迟跳转，让用户看到成功提示
          setTimeout(() => {
            isForgotPasswordMode.value = false
            // 清空表单
            forgotPasswordForm.username = ''
            forgotPasswordForm.phone = ''
            forgotPasswordForm.newPassword = ''
            forgotPasswordForm.confirmPassword = ''
          }, 1500)
        } else {
          showToast(result.message || '密码重置失败，请检查账号或手机号', 'error')
        }
      } catch (error) {
        console.error('密码重置请求失败:', error)
        showToast(error.message || '网络错误，请检查后端服务是否启动', 'error')
      } finally {
        loading.value = false
      }
    }

    // 获取 Toast 图标
    const getToastIcon = (type) => {
      const icons = {
        success: 'toast-success-icon',
        error: 'toast-error-icon',
        warning: 'toast-warning-icon',
        info: 'toast-info-icon'
      }
      return icons[type] || icons.info
    }

    return {
      loginForm,
      registerForm,
      forgotPasswordForm,
      loading,
      isRegisterMode,
      isForgotPasswordMode,
      toast,
      handleLogin,
      handleRegister,
      handleForgotPassword,
      goToRegister,
      goToLogin,
      goToCustomerLogin,
      goToForgotPassword,
      showToast,
      getToastIcon
    }
  }
}
</script>

<style scoped>
/* 全局重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
}

/* 商家登录容器 */
.seller-login-container {
  display: flex;
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
}

/* 左侧品牌区域 - 商家后台主题色 */
.left-section {
  width: 38vw;
  height: 100vh;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.brand-content {
  text-align: center;
  max-width: 90%;
  padding: 20px;
}

.brand-title {
  font-size: 48px;
  font-weight: 700;
  margin-bottom: 20px;
  letter-spacing: 2px;
}

.brand-subtitle {
  font-size: 18px;
  margin-bottom: 40px;
  opacity: 0.9;
  line-height: 1.6;
}

.features {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 16px;
  background: rgba(255, 255, 255, 0.1);
  padding: 15px 20px;
  border-radius: 10px;
  backdrop-filter: blur(10px);
}

.feature-icon {
  font-size: 24px;
}

/* 右侧登录区域 */
.right-section {
  width: 62vw;
  height: 100vh;
  background: #f8f9fa;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 40px;
  flex-shrink: 0;
  overflow-y: auto;
  overflow-x: hidden;
  min-height: 100vh;
}

.login-content {
  width: 100%;
  max-width: 420px;
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  margin: 20px 0;
  min-height: fit-content;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h2 {
  font-size: 32px;
  color: #1e3c72;
  margin-bottom: 10px;
  font-weight: 600;
}

.login-header p {
  color: #666;
  font-size: 16px;
}

/* 注册表单头部 */
.register-header {
  text-align: center;
  margin-bottom: 40px;
}

.register-header h2 {
  font-size: 32px;
  color: #1e3c72;
  margin-bottom: 10px;
  font-weight: 600;
}

.register-header p {
  color: #666;
  font-size: 16px;
}

/* 登录表单 */
.login-form {
  width: 100%;
}

/* 注册表单 */
.register-form {
  width: 100%;
}

.form-group {
  margin-bottom: 20px;
}

.form-input {
  width: 100%;
  height: 50px;
  padding: 0 15px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s;
  background: #f8f9fa;
}

.form-input:focus {
  outline: none;
  border-color: #1e3c72;
  background: white;
  box-shadow: 0 0 0 3px rgba(30, 60, 114, 0.1);
}

.form-input::placeholder {
  color: #999;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.checkbox-wrapper input[type="checkbox"] {
  margin-right: 8px;
  width: 16px;
  height: 16px;
}

.forgot-password {
  color: #1e3c72;
  text-decoration: none;
  font-size: 14px;
}

.forgot-password:hover {
  text-decoration: underline;
}

.login-button {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 30px;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(30, 60, 114, 0.3);
}

.login-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

/* 注册按钮 */
.register-button {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 30px;
}

.register-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(30, 60, 114, 0.3);
}

.register-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.register-link {
  text-align: center;
  margin-bottom: 30px;
  color: #666;
  font-size: 14px;
}

.register-link a {
  color: #1e3c72;
  text-decoration: none;
  font-weight: 500;
}

.register-link a:hover {
  text-decoration: underline;
}

/* 登录链接 */
.login-link {
  text-align: center;
  margin-bottom: 30px;
  color: #666;
  font-size: 14px;
}

.login-link a {
  color: #1e3c72;
  text-decoration: none;
  font-weight: 500;
}

.login-link a:hover {
  text-decoration: underline;
}

/* 条款链接 */
.terms-link {
  color: #1e3c72;
  text-decoration: none;
}

.terms-link a:hover {
  text-decoration: underline;
}

.help-section {
  margin-top: 30px;
}

.divider {
  text-align: center;
  margin-bottom: 20px;
  position: relative;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #e4e7ed;
}

.divider span {
  background: white;
  padding: 0 20px;
  color: #999;
  font-size: 14px;
}

.help-buttons {
  display: flex;
  gap: 15px;
}

.help-btn {
  flex: 1;
  height: 45px;
  border: 2px solid #e4e7ed;
  background: white;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.help-btn:hover {
  border-color: #1e3c72;
  color: #1e3c72;
}

.help-icon {
  font-size: 18px;
}

/* 客户登录入口样式 */
.customer-entrance {
  margin-top: 30px;
}

.customer-login-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 16px;
  font-weight: 500;
}

.customer-login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.customer-icon {
  font-size: 20px;
}

/* Toast 提示样式 */
.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 9999;
  min-width: 300px;
  max-width: 500px;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  animation: slideInRight 0.3s ease-out;
  transition: all 0.3s ease;
}

.toast.success {
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
  border-left: 4px solid #2e7d32;
}

.toast.error {
  background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
  color: white;
  border-left: 4px solid #c62828;
}

.toast.warning {
  background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
  color: white;
  border-left: 4px solid #ef6c00;
}

.toast.info {
  background: linear-gradient(135deg, #2196F3 0%, #1976d2 100%);
  color: white;
  border-left: 4px solid #1565c0;
}

.toast-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.toast-icon {
  font-size: 20px;
  flex-shrink: 0;
}

.toast-success-icon::before {
  content: '✓';
}

.toast-error-icon::before {
  content: '✕';
}

.toast-warning-icon::before {
  content: '⚠';
}

.toast-info-icon::before {
  content: 'ℹ';
}

.toast-message {
  font-size: 14px;
  line-height: 1.4;
  font-weight: 500;
}

@keyframes slideInRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .seller-login-container {
    flex-direction: column;
  }

  .left-section,
  .right-section {
    width: 100vw;
  }

  .left-section {
    height: 30vh;
  }

  .right-section {
    height: 70vh;
    padding: 20px;
  }

  .login-content {
    padding: 30px 20px;
  }

  .brand-title {
    font-size: 36px;
  }

  .features {
    flex-direction: row;
    justify-content: space-around;
    flex-wrap: wrap;
  }

  .feature-item {
    flex-direction: column;
    text-align: center;
    padding: 10px;
    font-size: 14px;
    width: 45%;
  }

  /* 移动端 Toast 样式调整 */
  .toast {
    top: 10px;
    right: 10px;
    left: 10px;
    min-width: auto;
    max-width: none;
    padding: 12px 16px;
  }

  .toast-message {
    font-size: 13px;
  }
}
</style>
